package com.evo.chat.admin.service.impl;

import com.evo.chat.admin.domain.AdminUser;
import com.evo.chat.admin.repository.AdminUserRepository;
import com.evo.chat.admin.service.AdminUserService;
import com.evo.chat.common.Result;
import com.evo.chat.common.ResultEnum;
import com.evo.chat.common.exception.ChatException;
import com.evo.chat.common.utils.Md5Util;
import com.evo.chat.common.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author luwenzheng
 * date 2020-02-06
 */
@Service
public class AdminUserServiceImpl implements AdminUserService {

    private final Logger logger = LoggerFactory.getLogger(AdminUserServiceImpl.class);

    @Autowired
    AdminUserRepository repository;

    @Override
    public Result createUser(String name, String password) {
        AdminUser adminUser = repository.findByName(name);
        if (adminUser != null) {
            return ResultUtil.error(ResultEnum.USER_HAS_EXIST);
        }

        adminUser = new AdminUser();
        adminUser.setName(name);
        adminUser.setPassword(password);
        repository.save(adminUser);
        return ResultUtil.success();
    }

    @Override
    public AdminUser login(String name, String password) {
        //通过用户的手机获取用户对象
        AdminUser adminUser = repository.findByName(name);
        if(adminUser == null){
            throw new ChatException(ResultEnum.USER_NOT_EXIST);
        }

        if(!password.equals(adminUser.getPassword())){
            throw new ChatException(ResultEnum.USER_PASSWORD_ERROR);
        }

        return adminUser;
    }
}
